//
//  FirstViewController.m
//  BangoiOSSDKTestApp
//
//  Created by Development Bango on 12/06/2013.
//  Copyright (c) 2013 Development Bango. All rights reserved.
//

#import "FirstViewController.h"
#import "AppDelegate.h"
#import "BGOProfile.h"
#import "BGOAnalyticsManager.h"
#import "BGOAnalyticsConstants.h"
#import "BangoConfigConstants.h"
#import "BGOTransmissionModeConstants.h"
#import "BGODataType.h"
#import "BGOEvent.h"
#import "BGOEventParameter.h"
#import "BGOPersistenceManager.h"
#import "LoggingLevelView.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize viewBatchTV;
@synthesize profiles=_profiles;
@synthesize entityName=entityName;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UITapGestureRecognizer *gestureRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [self.tableView addGestureRecognizer:gestureRecogniser];
	// Do any additional setup after loading the view, typically from a nib.
    [BGOAnalyticsManager sharedManager].logEnabled = YES;
    [BGOAnalyticsManager sharedManager].eventThrottling = YES;
    if(self.entityName == nil){
        self.entityName = @"Profile";
    }
}

-(void)hideKeyboard {
    [self.eventNameTf resignFirstResponder];
    [self.eventValueTf resignFirstResponder];
    [self.eventDetailTf resignFirstResponder];
    [self.parameter1Tf resignFirstResponder];
    [self.parameter1ValTf resignFirstResponder];
    [self.parameter2Tf resignFirstResponder];
    [self.parameter2ValTf resignFirstResponder];
}
-(void) viewWillAppear:(BOOL)animated{
    [BGOAnalyticsManager sharedManager].delegate = self;
    if(self.profiles == nil){
    [self loadProfiles];
    }

}

-(BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationMaskPortrait);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)lvStartBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"live video start emulation", BGO_VIDEO_PARAMETERNAME, @"live video custom value", BGO_VIDEO_LIVEPARAMETER, nil];
    [[BGOAnalyticsManager sharedManager] onLiveVideoStartWithEventParameters:eventParameters eventDetail:@"live video event detail" eventValue:@"live video event value"];
    [self loadProfiles];
}

- (IBAction)lvStopBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"live video stop emulation", BGO_VIDEO_PARAMETERNAME, @"live video custom value", BGO_VIDEO_LIVEPARAMETER, nil];
    [[BGOAnalyticsManager sharedManager] onLiveVideoStopWithEventParameters:eventParameters eventDetail:@"live video stop event detail" eventValue:@"live video stop event value"];
    [self loadProfiles];
}

- (IBAction)searchBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"search emulation", @"search emulation", @"search custom value", @"search custom value", nil];
    [[BGOAnalyticsManager sharedManager] onSearchWithEventParameters:eventParameters eventDetail:@"search event detail" eventValue:@"search event value"];
    [self loadProfiles];
}

- (IBAction)logLevelBtnPressed:(id)sender {
    
    LoggingLevelView *loggingLevelVC=[[LoggingLevelView alloc]init];
    [self presentViewController:loggingLevelVC animated:YES completion:nil];
    
}

- (IBAction)odStartBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"on demand video start emulation", BGO_VIDEO_PARAMETERNAME, @"search custom value", BGO_VIDEO_ONDEMANDPARAMETER, nil];
    [[BGOAnalyticsManager sharedManager] onDemandVideoStartWithEventParameters:eventParameters eventDetail:@"on demand event detail" eventValue:@"on demand event value"];
    [self loadProfiles];
}

- (IBAction)odStopBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"on demand stop emulation", BGO_VIDEO_PARAMETERNAME, @"on demand stop custom value",BGO_VIDEO_ONDEMANDPARAMETER, nil];
    [[BGOAnalyticsManager sharedManager] onDemandVideoStopWithEventParameters:eventParameters eventDetail:@"on demand stop detail" eventValue:@"on demand stop value"];
    [self loadProfiles];
}

- (IBAction)pgViewBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"page view emulation", @"BGO_PAGE_VIEW", @"page view custom value",@"BGO_PAGE_VIEW_PARAMETER", nil];
    [[BGOAnalyticsManager sharedManager] onPageViewWithEventParameters:eventParameters eventDetail:@"page view event detail" eventValue:@"page view event value"];
    [self loadProfiles];
}

- (IBAction)postBtnPressed:(id)sender {
     NSLog(@"> %s", __PRETTY_FUNCTION__);
    [[BGOAnalyticsManager sharedManager] commenceTransmissionWithMode:BGO_TRANSMIT_ALL];
}

- (IBAction)idleBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"on idle emulation", @"BGO_ON_IDLE", @"on idle custom value",@"BGO_ON_IDLE_PARAMETER", nil];
    [[BGOAnalyticsManager sharedManager] onIdleWithEventParameters:eventParameters eventDetail:@"on idle event detail" eventValue:@"on idle event value"];
}

- (IBAction)resumeBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys: @"on resume emulation", @"BGO_ON_RESUME", @"on resume custom value",@"BGO_ON_RESUME_PARAMETER", nil];
    [[BGOAnalyticsManager sharedManager] onResumeWithEventParameters:eventParameters eventDetail:@"on resume event detail" eventValue:@"on resume event value"];
    [self loadProfiles];
}

- (IBAction)logBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSString *param1 = self.parameter1Tf.text;
    NSString *param1Value = self.parameter1ValTf.text;
    NSString *param2 = self.parameter2Tf.text;
    NSString *param2Value = self.parameter2ValTf.text;
    NSString *eventName = self.eventNameTf.text;
    NSString *eventValue = self.eventValueTf.text;
    NSString *eventDetail = self.eventDetailTf.text;
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys:param1, param1Value, param2, param2Value, nil];
    [[BGOAnalyticsManager sharedManager] onEvent:eventName eventDetail:eventDetail eventValue:eventValue eventParameters:eventParameters];
    UIAlertView *ok = [[UIAlertView alloc] initWithTitle:@"Event Log" message:@"Your event has been logged" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [ok show];
}

- (IBAction)exitBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"End session test", @"BGO_APP_SESSION_END", @"end session custom value", @"BGO_CUSTOM1", nil];
    [[BGOAnalyticsManager sharedManager] onEndSessionWithEventParameters:eventParameters eventDetail:@"test app end session detail" eventValue:@"test app end session value"];
    [self loadProfiles];
}

- (IBAction)resetBtnPressed:(id)sender {
    self.eventNameTf.text = @"iOS EVENT";
    self.eventDetailTf.text = @"iOS EVENT DETAIL";
    self.eventValueTf.text = @"iOS EVENT VALUE";
    self.parameter1Tf.text = @"BGO_SOURCE";
    self.parameter1ValTf.text = @"iOS SOURCE";
    self.parameter2Tf.text = @"BGO_TERM";
    self.parameter2ValTf.text = @"iOS TERM";
}

- (IBAction)clearBtnPressed:(id)sender {
    self.eventNameTf.text = @"";
    self.eventDetailTf.text = @"";
    self.eventValueTf.text = @"";
    self.parameter1Tf.text = @"";
    self.parameter1ValTf.text = @"";
    self.parameter2Tf.text = @"";
    self.parameter2ValTf.text = @"";
}

- (IBAction)errorBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
	NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"error emulation",
                                     @"BGO_ERROR",
                                     @"error custom value",
                                     @"BGO_CUSTOM1",
                                     nil];
	
	NSNumber *errorLevel = [NSNumber numberWithInt:BGO_ERROR_USER];
	NSString *errorId = @"SuperBadError(TEST)";
    
	[[BGOAnalyticsManager sharedManager] onErrorWithEventParameters:eventParameters message:@"test app detail -emulating error" eventClass:@"test app value - emulating on error"
                                                    eventErrorLevel:errorLevel eventErrorId:errorId];
    [self loadProfiles];

}

- (IBAction)viewBatchBtnPressed:(id)sender {
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    self.profiles = [[BGOPersistenceManager sharedPersistenceManager] getProfilesForPost:NO bangoUserId:[BGOAnalyticsManager sharedManager].bangoUserId];
    NSMutableString *textViewText = [NSMutableString string];
    if(self.profiles == nil){
        [textViewText appendString:@"No events for this profile"];
    }
    else{
        for(BGOProfile *profile in self.profiles){
            [textViewText appendFormat:@"%@", profile.applicationKey];
            [textViewText appendFormat:@" Events: %lu", (unsigned long)profile.events.count];
            [textViewText appendString:@"\n"];
            for(BGOEvent *event in profile.events){
                [textViewText appendFormat:@" %@", event.eventName];
                [textViewText appendString:@"\n"];
            }
            [textViewText appendString:@"\n"];
        }
    }

    self.viewBatchTV.text = textViewText;
}

- (IBAction)logMultipleBtnPressed:(id)sender {
    UIAlertView *numberOfEventsPrompt = [[UIAlertView alloc] initWithTitle:@"Enter amount of events to log" message:@"Events" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    [numberOfEventsPrompt setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [numberOfEventsPrompt show];
}

-(void) loadProfiles{
    NSLog(@"> %s", __PRETTY_FUNCTION__);
    self.profiles = [[BGOPersistenceManager sharedPersistenceManager] getProfilesForPost:NO bangoUserId:[BGOAnalyticsManager sharedManager].bangoUserId];
    BGOProfile *profile = (BGOProfile *)[_profiles objectAtIndex:0];
    BGOEvent *event = (BGOEvent *)[profile.events objectAtIndex:0];
    NSMutableString *textViewText = [NSMutableString string];
    [textViewText appendFormat:@"%@", profile.applicationKey];
    [textViewText appendFormat:@" Events: %lu", (unsigned long)profile.events.count];
    [textViewText appendFormat:@" %@", event.eventName];    
    
    
    //check userInterfaceIdiom for which textview to populate.
}

#pragma mark Delegate optional methods
- (void)transmitFailure{
    UIAlertView * warningView = [[UIAlertView alloc] initWithTitle:@"Warning"
                                                            message:@"Your transmission has failed"
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
    
    [warningView show];
}

- (void) transmitSuccess {
    [self loadProfiles];
    
}

- (void)viewDidUnload {
    [self setLogMultipleEvents:nil];
    [super viewDidUnload];
}

#pragma mark UIAlertView delegate methods

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"OK"])
    {
        NSLog(@"OK selected");
        NSString *numberOfEvents = [[alertView textFieldAtIndex:0] text];
        int eventsToLog = [numberOfEvents intValue];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
            for (int i = 1; i <= eventsToLog; i++) {
                NSDictionary *eventParameters = [[NSDictionary alloc] initWithObjectsAndKeys:@"parameter1", @"parameter1Value", @"parameter2", @"parameter2Value", nil];
                NSString *eventDetail = [NSString stringWithFormat:@"iOS Test Event %d : %@", i, [self GetUUID]];
                [[BGOAnalyticsManager sharedManager] onEvent:@"IOS Test Event" eventDetail:eventDetail eventValue:@"Event Value" eventParameters:eventParameters];

            }
            
            dispatch_async(dispatch_get_main_queue(), ^(void){
                NSString *eventsLogged = [NSString stringWithFormat:@"%d events have been logged", eventsToLog];
                UIAlertView *done = [[UIAlertView alloc] initWithTitle:@"Events Logged" message:eventsLogged delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [done show];
                
            });
        });
    }
    
}

-(BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if([inputText length] > 0)
    {
        return YES;
    }
    else{
        return NO;
    }
}

-(NSString *)GetUUID{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return (__bridge NSString *)string;
}











@end
